package universe;

public class BlockHandler {
	private int x;
	private int y;
	
	private int yClone;
	
	private Block b;
	private Board board;
	
	private boolean visible = true;


	public BlockHandler(Block pBlock, Board pBoard){
		this.setBoard(pBoard);
		this.setB(pBlock);
		this.setX((int)((this.getBoard().getWidth()/2)-2));
		this.setY(0);
		this.resetClone();
		
	}
	
	public void resetClone(){
		this.setYClone(0);
		this.dropDownClone();
	}

	public boolean dropDown(){
		boolean bReturn = board.pushAllowed(b, x, y+1);

		while(goDown());

		return bReturn;
	}
	
	public boolean dropDownClone(){
		this.yClone = this.y;
		boolean bReturn = board.pushAllowed(b, x, yClone+1);

		while(goDownClone());

		return bReturn;
	}


	public boolean goDown(){
		boolean bReturn = (board.pushAllowed(b, x, y+1));

		if(bReturn)
			this.setY(this.getY()+1);	

		return bReturn;

	}
	
	public boolean goDownClone(){
		boolean bReturn = (board.pushAllowed(b, x, yClone+1));

		if(bReturn)
			this.setYClone(this.getYClone()+1);	

		return bReturn;

	}

	public boolean goLeft()
	{
		boolean bReturn = (board.pushAllowed(b, x-1, y));

		if(bReturn)
			this.setX(this.getX()-1);	

		return bReturn;

	}

	public boolean goRight(){

		boolean bReturn = (board.pushAllowed(b, x+1, y));

		if(bReturn)
			this.setX(this.getX()+1);	

		return bReturn;

	}

	public void rotate(){
		//int oldX = this.getX();
		//int oldY = this.getY();
		int oldPosition = this.getB().getCurrentPosition();

		this.getB().rotate();

		if(!this.board.pushAllowed(this.b, this.getX(), this.getY())){

			// est on bloqué a droite ?
			//peut on décaler a gauche
			if(this.getBoard().pushAllowed(getB(), getX()-1, getY())){
				//Si oui on decale a gauche
				this.setX(getX()-1);
			}
			else{

				if(this.getBoard().pushAllowed(getB(), getX()-2, getY())){
					//Si oui on decale de 2 cases a gauche
					this.setX(getX()-2);
				}
				else{
					if(this.getBoard().pushAllowed(getB(), getX()-3, getY())){
						//Si oui on decale de 3 cases a gauche
						this.setX(getX()-3);
					}else{
						// alors on ne decale pas la piece a gauche
						this.getB().setCurrentPosition(oldPosition);

					}
				}
			}

		}
		resetClone();
	}


	//Getters and Setters
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
		dropDownClone();
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
		dropDownClone();
	}
	
	public int getYClone() {
		return yClone;
	}

	public void setYClone(int pYClone) {
		this.yClone = pYClone;
	}

	public Block getB() {
		return b;
	}

	public void setB(Block b) {
		this.b = b;
	}

	public Board getBoard() {
		return board;
	}

	public void setBoard(Board board) {
		this.board = board;
	}

	/*public void clear(){
		b = null;
		board = null;		
	}*/

	public boolean isVisible() {
		return visible;
	}

	public void setVisible(boolean visible) {
		this.visible = visible;
	}
}
